# coding: utf-8

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext

from decorators import member_required
from models import SharedAccount, AccountTransaction, MemberAccount
from forms import AccountForm, AddMemberForm, EditMemberForm, DepositForm, DrawForm, PayForm, DepositAndPayForm, TransferForm

def index(request, template_name='index.html'):
    logined = request.user.is_authenticated()
    if logined and request.GET.get('noredirect') is None:
        return HttpResponseRedirect('/sa/')
    has_accounts = False
    if logined:
        has_accounts = len(request.user.shared_account_ids) > 0

    return render_to_response(template_name, {
            'logined': logined,
            'has_accounts': has_accounts,
        }, context_instance=RequestContext(request)
    )
    
@login_required
def account_list(request, template_name='shared_accounting/list.html'):
    accounts = SharedAccount.get_by_id(request.user.shared_account_ids)
    return render_to_response(template_name, {
            'accounts': accounts[::-1],
        }, context_instance=RequestContext(request)
    )

@member_required
def account_detail(request, account, current_member, template_name='shared_accounting/detail.html'):
    return render_to_response(template_name, {
            'account': account,
        }, context_instance=RequestContext(request)
    )

@login_required
def account_new(request, form_class=AccountForm, template_name='shared_accounting/new.html'):
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            account = form.save(request)
            messages.success(request, u'帐户已创建')
            return HttpResponseRedirect('/sa/%s/edit/' % account.id)
    else:
        form = form_class()

    return render_to_response(template_name, {
            'form': form,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_edit(request, account, current_member, form_class=AccountForm, template_name='shared_accounting/edit.html'):
    if request.method == 'POST':
        form = form_class(request.POST, instance=account)
        if form.is_valid():
            account = form.save(request, instance=account)
            messages.success(request, u'帐户已保存')
            return HttpResponseRedirect('/sa/%s/edit/' % account.id)
    else:
        form = form_class(instance=account)

    return render_to_response(template_name, {
            'form': form,
            'account': account,
            'members': account.get_members(),
        }, context_instance=RequestContext(request)
    )

@member_required
def account_member_add(request, account, current_member, form_class=AddMemberForm, template_name='shared_accounting/member_edit.html'):
    if request.method == 'POST':
        form = form_class(request.POST, account=account)
        if form.is_valid():
            form.add_member()
            messages.success(request, u'成员已添加')
            return HttpResponseRedirect('/sa/%s/edit/' % account.id)
    else:
        form = form_class()
    return render_to_response(template_name, {
            'form': form,
            'account': account,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_member_edit(request, account, current_member, member_id, form_class=EditMemberForm, template_name='shared_accounting/member_edit.html'):
    member_id = int(member_id)
    if member_id not in account.member_ids:
        raise Http404
    member = MemberAccount.get_by_id(member_id)
    if member is None:
        raise Http404
    if request.method == 'POST':
        form = form_class(request.POST, account=account, instance=member)
        if form.is_valid():
            member = form.update_member()
            messages.success(request, u'成员已保存')
            return HttpResponseRedirect('/sa/%s/edit/' % account.id)
    else:
        form = form_class(account=account, instance=member)
    return render_to_response(template_name, {
            'form': form,
            'account': account,
            'member': member,
            'edit': True,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_member_delete(request, account, current_member, member_id):
    member_id = int(member_id)
    if member_id not in account.member_ids:
        raise Http404
    member = MemberAccount.get_by_id(member_id)
    if member is None:
        raise Http404
    if account.creator.id == member.user.id:
        raise HttpResponseForbidden(u'不能删除创建者')
    if member.transactions > 0:
        messages.error(request, u'该成员已有交易，不能删除')
        return HttpResponseRedirect('/sa/%d/edit/' % account.id)
    account.remove_member(member)
    messages.info(request, u'成员已删除')
    return HttpResponseRedirect('/sa/%d/edit/' % account.id)

@member_required
def account_delete(request, account, current_member):
    # delete all member accounts first
    for mem in account.get_members():
        user = mem.user
        user.shared_account_ids.remove(account.id)
        user.put()
        mem.delete()
    account.delete()
    messages.info(request, u'帐户已删除')
    return HttpResponseRedirect('/sa/')

def _account_deposit(request, account, current_member, form_class=DepositForm, 
            template_name='shared_accounting/deposit.html',
            save_message=u'成功从帐户%s存入%s元'):
    if request.method == 'POST':
        form = form_class(account, current_member, data=request.POST)
        if form.is_valid():
            deposit = form.save()
            messages.success(request, save_message % (deposit.member.name, deposit.amount))
            return HttpResponseRedirect('/sa/%s/' % account.id)
    else:
        form = form_class(account, current_member)
    return render_to_response(template_name, {
            'account': account,
            'form': form,
        }, context_instance=RequestContext(request)
    )
account_deposit = member_required(_account_deposit)

@member_required
def account_draw(request, account, current_member, form_class=DrawForm, template_name='shared_accounting/draw.html',
                  save_message=u'成功从帐户%s取出%s元'):
    return _account_deposit(request, account, current_member, form_class, template_name, save_message)

@member_required
def account_pay(request, account, current_member, form_class=PayForm, template_name='shared_accounting/pay.html',
                save_message=u'成功支付%s元'):
    if request.method == 'POST':
        form = form_class(account, current_member, data=request.POST)
        if form.is_valid():
            pay = form.save()
            messages.success(request, save_message % pay.amount)
            return HttpResponseRedirect('/sa/%s/' % account.id)
    else:
        form = form_class(account, current_member)
    return render_to_response(template_name, {
            'account': account,
            'form': form,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_deposit_and_pay(request, account, current_member, form_class=DepositAndPayForm,
                            template_name='shared_accounting/deposit_and_pay.html', save_message=u'成功支付%s元'):
    if request.method == 'POST':
        form = form_class(account, current_member, data=request.POST)
        if form.is_valid():
            pay = form.save()
            messages.success(request, save_message % pay.amount)
            return HttpResponseRedirect('/sa/%s/' % account.id)
    else:
        form = form_class(account, current_member)
    return render_to_response(template_name, {
            'account': account,
            'form': form,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_transfer(request, account, current_member, form_class=TransferForm,
                 template_name='shared_accounting/transfer.html', save_message=u'成功转账%s元'):
    if request.method == 'POST':
        form = form_class(account, current_member, data=request.POST)
        if form.is_valid():
            transfer = form.save()
            messages.success(request, save_message % transfer.amount)
            return HttpResponseRedirect('/sa/%s/' % account.id)
    else:
        form = form_class(account, current_member)
    return render_to_response(template_name, {
            'account': account,
            'form': form,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_transactions(request, account, current_member, template_name='shared_accounting/transactions.html'):
    trans = AccountTransaction.all().filter('account =', account).order('-created')
    return render_to_response(template_name, {
            'account': account,
            'transactions': trans,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_transaction_detail(request, account, current_member, trans_id, template_name='shared_accounting/transaction_detail.html'):
    trans_id = long(trans_id)
    trans = AccountTransaction.get_by_id(trans_id)
    if trans is None:
        raise Http404()
    return render_to_response(template_name, {
            'account': account,
            'transaction': trans,
        }, context_instance=RequestContext(request)
    )

@member_required
def account_transaction_delete(request, account, current_member, trans_id):
    trans_id = long(trans_id)
    trans = AccountTransaction.get_by_id(trans_id)
    if trans is None:
        raise Http404()
    trans.remove()
    messages.success(request, u'交易已成功删除')
    return HttpResponseRedirect('/sa/%s/transactions/' % account.id)

